const Koa = require("koa");
const Router = require("koa-router");
const bodyParser = require('koa-bodyparser');
const axios = require("axios");
const CryptoJS = require("crypto-js");
const session = require("koa-session");
const serverConfig = require("./server_config");
const serverUtil = require("./server_util");
const lark = require("@larksuiteoapi/node-sdk");
// const sql = require('mssql');
const { Connection, Request } = require("tedious");
// const dbConfig = {
//   user: 'sa',
//   password: '12345678',
//   server: 'localhost',
//   database: 'MyDatabase1',
//   options: {
//     encrypt: true,      // 启用加密（Azure SQL 必须为 true）
//     trustServerCertificate: true  // 信任自签名证书（开发环境适用）
//   }
// };

const dbConfig = {
  authentication: {
    options: {
      userName: "sa", // update me
      password: "12345678" // update me
    },
    type: "default"
  },
  server: "192.168.173.96", // update me
  options: {
    database: "MyDatabase1", //update me
    encrypt: true,
    trustServerCertificate: true
  }
};

const Dysmsapi20170525 = require('@alicloud/dysmsapi20170525');
const Util = require('@alicloud/tea-util');
const Client = require('./ali_sms');

const LJ_JSTICKET_KEY = "lk_jsticket";
const LJ_TOKEN_KEY = "lk_token";



//多维表格数据表数据
let tableData = [];


const connection = new Connection(dbConfig);

// 尝试建立连接
connection.on('connect', err => {
  if (err) {
      console.error('连接错误:', err.message);
  } else {
      console.log('成功连接到数据库');
      // 成功连接后执行查询
      executeQuery();
  }
});

connection.on('error', err => {
  console.error('连接错误:', err.message);
});

// 执行查询
function executeQuery() {
  const request = new Request(
      "SELECT * FROM student", // 替换为你的查询语句
      (err, rowCount) => {
          if (err) {
              console.error('执行查询时出错:', err.message);
          } else {
              console.log(`${rowCount} 行被返回`);
          }
          // 关闭连接
          connection.close();
      }
  );

  // 处理结果集
  request.on('row', columns => {
      columns.forEach(column => {
          console.log(column.metadata.colName + ': ' + column.value);
      });
  });

  // 执行请求
  connection.execSql(request);
}

// 监听连接关闭事件
connection.on('end', () => {
  console.log('数据库连接已关闭');
});

// 开始连接
connection.connect();

//处理免登请求，返回用户的user_access_token
async function getUserAccessToken(ctx) {
  console.log(
    "\n-------------------[接入服务端免登处理 BEGIN]-----------------------------"
  );
  // serverUtil.configAccessControl(ctx);
  console.log(`接入服务方第① 步: 接收到前端免登请求`);
  const accessToken = ctx.session.userinfo;
  const lkToken = ctx.cookies.get(LJ_TOKEN_KEY) || "";
  if (
    accessToken &&
    accessToken.access_token &&
    lkToken.length > 0 &&
    accessToken.access_token == lkToken
  ) {
    console.log(
      "接入服务方第② 步: 从Session中获取user_access_token信息，用户已登录"
    );
    ctx.body = serverUtil.okResponse(accessToken);
    console.log(
      "-------------------[接入服务端免登处理 END]-----------------------------\n"
    )
    return;
  }

  let code = ctx.query["code"] || "";
  console.log("接入服务方第② 步: 获取登录预授权码code");
  if (code.length == 0) {
    //code不存在
    ctx.body = serverUtil.failResponse(
      "登录预授权码code is empty, please retry!!!"
    );
    return;
  }

  //【请求】app_access_token：https://open.feishu.cn/document/ukTMukTMukTM/ukDNz4SO0MjL5QzM/auth-v3/auth/app_access_token_internal
  console.log(
    "接入服务方第③ 步: 根据AppID和App Secret请求应用授权凭证app_access_token"
  );
  const internalRes = await axios.post(
    "https://open.feishu.cn/open-apis/auth/v3/app_access_token/internal",
    {
      app_id: serverConfig.config.appId,
      app_secret: serverConfig.config.appSecret,
    },
    { headers: { "Content-Type": "application/json" } }
  );

  if (!internalRes.data) {
    ctx.body = serverUtil.failResponse("app_access_token request error");
    return;
  }
  if (internalRes.data.code != 0) {
    //非0表示失败
    ctx.body = serverUtil.failResponse(
      `app_access_token request error: ${internalRes.data.msg}`
    );
    return;
  }

  console.log("接入服务方第④ 步: 获得颁发的应用授权凭证app_access_token");
  const app_access_token = internalRes.data.app_access_token || "";

  console.log(
    "接入服务方第⑤ 步: 根据登录预授权码code和app_access_token请求用户授权凭证user_access_token"
  );
  //【请求】user_access_token: https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/authen-v1/access_token/create
  const authenv1Res = await axios.post(
    "https://open.feishu.cn/open-apis/authen/v1/access_token", //历史版本
    { grant_type: "authorization_code", code: code },
    {
      headers: {
        "Content-Type": "application/json; charset=utf-8",
        Authorization: "Bearer " + app_access_token,
      },
    }
  );

  if (!authenv1Res.data) {
    ctx.body = serverUtil.failResponse("access_toke request error");
    return;
  }
  if (authenv1Res.data.code != 0) {
    //非0表示失败
    ctx.body = serverUtil.failResponse(
      `access_toke request error: ${authenv1Res.data.msg}`
    );
    return;
  }

  console.log(
    "接入服务方第⑥ 步: 获取颁发的用户授权码凭证的user_access_token, 更新到Session，返回给前端"
  );
  const newAccessToken = authenv1Res.data.data;
  console.log("newAccessToken", newAccessToken);
  if (newAccessToken) {
    ctx.session.userinfo = newAccessToken;
    serverUtil.setCookie(ctx, LJ_TOKEN_KEY, newAccessToken.access_token || "");
  } else {
    serverUtil.setCookie(ctx, LJ_TOKEN_KEY, "");
  }

  ctx.body = serverUtil.okResponse(newAccessToken);
  console.log(
    "-------------------[接入服务端免登处理 END]-----------------------------\n"
  );
}

//处理鉴权参数请求，返回鉴权参数
async function getSignParameters(ctx) {
  console.log(
    "\n-------------------[接入方服务端鉴权处理 BEGIN]-----------------------------"
  );
  // serverUtil.configAccessControl(ctx);
  console.log(`接入服务方第① 步: 接收到前端鉴权请求`);

  const url = ctx.query["url"] || "";
  const tickeString = ctx.cookies.get(LJ_JSTICKET_KEY) || "";
  if (tickeString.length > 0) {
    console.log(
      `接入服务方第② 步: Cookie中获取jsapi_ticket，计算JSAPI鉴权参数，返回`
    );
    const signParam = calculateSignParam(tickeString, url);
    ctx.body = serverUtil.okResponse(signParam);
    console.log(
      "-------------------[接入方服务端鉴权处理 END]-----------------------------\n"
    );
    return;
  }

  console.log(
    `接入服务方第② 步: 未检测到jsapi_ticket，根据AppID和App Secret请求自建应用授权凭证tenant_access_token`
  );
  //【请求】tenant_access_token：https://open.feishu.cn/document/ukTMukTMukTM/ukDNz4SO0MjL5QzM/auth-v3/auth/tenant_access_token_internal
  const internalRes = await axios.post(
    "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal",
    {
      app_id: serverConfig.config.appId,
      app_secret: serverConfig.config.appSecret,
    },
    { headers: { "Content-Type": "application/json" } }
  );

  if (!internalRes.data) {
    ctx.body = serverUtil.failResponse("tenant_access_token request error");
    return;
  }
  if (internalRes.data.code != 0) {
    ctx.body = serverUtil.failResponse(
      `tenant_access_token request error: ${internalRes.data.msg}`
    );
    return;
  }

  console.log(
    `接入服务方第③ 步: 获得颁发的自建应用授权凭证tenant_access_token`
  );
  const tenant_access_token = internalRes.data.tenant_access_token || "";

  console.log(`接入服务方第④ 步: 请求JSAPI临时授权凭证`);
  //【请求】jsapi_ticket：https://open.feishu.cn/document/ukTMukTMukTM/uYTM5UjL2ETO14iNxkTN/h5_js_sdk/authorization
  const ticketRes = await axios.post(
    "https://open.feishu.cn/open-apis/jssdk/ticket/get",
    {},
    {
      headers: {
        "Content-Type": "application/json; charset=utf-8",
        Authorization: "Bearer " + tenant_access_token,
      },
    }
  );

  if (!ticketRes.data) {
    ctx.body = serverUtil.failResponse("get jssdk ticket request error");
    return;
  }
  if (ticketRes.data.code != 0) {
    //非0表示失败
    ctx.body = serverUtil.failResponse(
      `get jssdk ticket request error: ${ticketRes.data.msg}`
    );
    return;
  }

  console.log(`接入服务方第⑤ 步: 获得颁发的JSAPI临时授权凭证，更新到Cookie`);
  const newTicketString = ticketRes.data.data.ticket || "";
  if (newTicketString.length > 0) {
    serverUtil.setCookie(ctx, LJ_JSTICKET_KEY, newTicketString);
  }

  console.log(`接入服务方第⑥ 步: 计算出JSAPI鉴权参数，并返回给前端`);
  const signParam = calculateSignParam(newTicketString, url);
  ctx.body = serverUtil.okResponse(signParam);
  console.log(
    "-------------------[接入方服务端鉴权处理 END]-----------------------------\n"
  );
}

//计算鉴权参数
function calculateSignParam(tickeString, url) {
  const timestamp = new Date().getTime();
  const verifyStr = `jsapi_ticket=${tickeString}&noncestr=${serverConfig.config.noncestr}&timestamp=${timestamp}&url=${url}`;
  let signature = CryptoJS.SHA1(verifyStr).toString(CryptoJS.enc.Hex);
  const signParam = {
    app_id: serverConfig.config.appId,
    signature: signature,
    noncestr: serverConfig.config.noncestr,
    timestamp: timestamp,
  };
  return signParam;
}

//获取多维表格指定数据表的数据
async function reqGetDuoWeiTableData(tenant_access_token) {
  const client = new lark.Client({
    appId: serverConfig.config.appId,
    appSecret: serverConfig.config.appSecret,
    disableTokenCache: true,
  });

  return await client.bitable.v1.appTableRecord.search(
    {
      path: {
        app_token: "Gku8bF1Z7aLYmgsCkXsccRb3nyd",
        table_id: "tblPT6wWAjPf8vY5",
      },
      params: {
        user_id_type: "open_id",
      },
      data: {
        // automatic_fields:true,
      },
    },
    lark.withTenantToken(tenant_access_token)
  );
}

async function getDuoWeiList(ctx) {
  //【请求】tenant_access_token：https://open.feishu.cn/document/ukTMukTMukTM/ukDNz4SO0MjL5QzM/auth-v3/auth/tenant_access_token_internal
  const internalRes = await axios.post(
    "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal",
    {
      app_id: serverConfig.config.appId,
      app_secret: serverConfig.config.appSecret,
    },
    { headers: { "Content-Type": "application/json" } }
  );

  if (!internalRes.data) {
    ctx.body = serverUtil.failResponse("tenant_access_token request error");
    return;
  }
  if (internalRes.data.code != 0) {
    ctx.body = serverUtil.failResponse(
      `tenant_access_token request error: ${internalRes.data.msg}`
    );
    return;
  }

  // console.log(`internalRes`, internalRes);

  console.log(
    `接入服务方第③ 步: 获得颁发的自建应用授权凭证tenant_access_token`,
    internalRes.data.tenant_access_token
  );
  const tenant_access_token = internalRes.data.tenant_access_token || "";

  //获取自建应用授权凭证tenant_access_token结束

  // serverUtil.configAccessControl(ctx);

  const duoweitable = await reqGetDuoWeiTableData(tenant_access_token);
  // console.log("duoweitable",duoweitable);
  if (duoweitable && duoweitable.data.items.length > 0) {
    console.log("多维表格数据:", duoweitable.data.items);
    tableData = duoweitable.data.items;
    ctx.body = duoweitable.data.items;
  } else {
    ctx.body = "多维表格数据为空!";
  }
}

//批量获取多维表格指定记录
async function reqGetTRecords(tenant_access_token, record_ids) {
  const client = new lark.Client({
    appId: serverConfig.config.appId,
    appSecret: serverConfig.config.appSecret,
    disableTokenCache: true,
  });

  return client.bitable.v1.appTableRecord.batchGet({
    path: {
      app_token: 'Gku8bF1Z7aLYmgsCkXsccRb3nyd',
      table_id: 'tblPT6wWAjPf8vY5',
    },
    data: {
      record_ids,
      user_id_type: 'open_id',
      with_shared_url: true,
      automatic_fields: true,
    },
  },
    lark.withTenantToken(tenant_access_token))
}

async function getTRecords(ctx) {
  //【请求】tenant_access_token：https://open.feishu.cn/document/ukTMukTMukTM/ukDNz4SO0MjL5QzM/auth-v3/auth/tenant_access_token_internal
  const internalRes = await axios.post(
    "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal",
    {
      app_id: serverConfig.config.appId,
      app_secret: serverConfig.config.appSecret,
    },
    { headers: { "Content-Type": "application/json" } }
  );

  if (!internalRes.data) {
    ctx.body = serverUtil.failResponse("tenant_access_token request error");
    return;
  }
  if (internalRes.data.code != 0) {
    ctx.body = serverUtil.failResponse(
      `tenant_access_token request error: ${internalRes.data.msg}`
    );
    return;
  }

  console.log(
    `接入服务方第③ 步: 获得颁发的自建应用授权凭证tenant_access_token`,
    internalRes.data.tenant_access_token
  );
  const tenant_access_token = internalRes.data.tenant_access_token || "";

  //获取自建应用授权凭证tenant_access_token结束

  // serverUtil.configAccessControl(ctx);

  const records = await reqGetTRecords(tenant_access_token, ctx.request.body);
  console.log("获取的记录数据:", records);
  // if (records && records.length > 0) {
  //   console.log("记录数据:", records.data.items);
  //   ctx.body = duoweitable.data.items;
  // } else {
  //   ctx.body = "记录数据为空!";
  // }
  ctx.body = records;
  // ctx.body = { message: 'POST 成功', success: true };
}

//更改多维表格指定数据表指定记录的数据
async function reqUpdateTRecord(tenant_access_token, record_id, longitude, latitude, timestamp) {
  // 开发者复制该Demo后，需要修改Demo里面的"app id", "app secret"为自己应用的appId, appSecret
  const client = new lark.Client({
    appId: serverConfig.config.appId,
    appSecret: serverConfig.config.appSecret,
    disableTokenCache: true,
  });

  return await client.bitable.v1.appTableRecord.update(
    {
      path: {
        app_token: "Gku8bF1Z7aLYmgsCkXsccRb3nyd",
        table_id: "tblPT6wWAjPf8vY5",
        record_id,
      },
      params: {
        user_id_type: "open_id",
        ignore_consistency_check: false,
      },
      data: {
        fields: { "外出签卡记录": `${longitude},${latitude}`, "外出签卡时间": Number(timestamp) }
      },
    },
    lark.withTenantToken(tenant_access_token)
  );
}

async function updateTRecord(ctx) {
  const internalRes = await axios.post(
    "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal",
    {
      app_id: serverConfig.config.appId,
      app_secret: serverConfig.config.appSecret,
    },
    { headers: { "Content-Type": "application/json" } }
  );

  if (!internalRes.data) {
    ctx.body = serverUtil.failResponse("tenant_access_token request error");
    return;
  }
  if (internalRes.data.code != 0) {
    ctx.body = serverUtil.failResponse(
      `tenant_access_token request error: ${internalRes.data.msg}`
    );
    return;
  }

  // console.log(`internalRes`, internalRes);

  console.log(
    `接入服务方第③ 步: 获得颁发的自建应用授权凭证tenant_access_token`,
    internalRes.data.tenant_access_token
  );
  const tenant_access_token = internalRes.data.tenant_access_token || "";

  //获取自建应用授权凭证tenant_access_token结束

  // serverUtil.configAccessControl(ctx);
  console.log("后端请求修改的经纬度", ctx.query.longitude, ctx.query.latitude);
  // const res = await reqUpdateTRecord(tenant_access_token,ctx.query.record_id,ctx.query.longitude,ctx.query.latitude);
  const res = await reqUpdateTRecord(tenant_access_token, ctx.query.record_id, ctx.query.longitude, ctx.query.latitude, ctx.query.timestamp);
  console.log("res", res);
  ctx.body = res;
  // if (res) {
  //   ctx.body = "修改记录成功";
  // } else {
  //   ctx.body = "修改记录失败!";
  // }
}

//调用指定技能-群消息分析
async function reqExecAilySkill(tenant_access_token) {
  const client = new lark.Client({
    appId: serverConfig.config.appId,
    appSecret: serverConfig.config.appSecret,
    disableTokenCache: true,
  });
  return await client.aily.v1.appSkill.start({
    path: {
      app_id: serverConfig.config.appId,
      skill_id: 'skill_bc6d72f098f1',
    }
  },
    lark.withTenantToken(tenant_access_token)
  )

}

async function execAilySkill() {
  const internalRes = await axios.post(
    "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal",
    {
      app_id: serverConfig.config.appId,
      app_secret: serverConfig.config.appSecret,
    },
    { headers: { "Content-Type": "application/json" } }
  );

  if (!internalRes.data) {
    ctx.body = serverUtil.failResponse("tenant_access_token request error");
    return;
  }
  if (internalRes.data.code != 0) {
    ctx.body = serverUtil.failResponse(
      `tenant_access_token request error: ${internalRes.data.msg}`
    );
    return;
  }

  // console.log(`internalRes`, internalRes);

  console.log(
    `接入服务方第③ 步: 获得颁发的自建应用授权凭证tenant_access_token`,
    internalRes.data.tenant_access_token
  );
  const tenant_access_token = internalRes.data.tenant_access_token || "";

  //获取自建应用授权凭证tenant_access_token结束
  // serverUtil.configAccessControl(ctx);
  const res = await reqExecAilySkill(tenant_access_token);
  console.log("执行技能的结果", res);
  ctx.body = { "result": "执行完成" };
}

//删除多维表格指定记录
async function reqDelTRecord(tenant_access_token, record_id) {
  // 开发者复制该Demo后，需要修改Demo里面的"app id", "app secret"为自己应用的appId, appSecret
  const client = new lark.Client({
    appId: serverConfig.config.appId,
    appSecret: serverConfig.config.appSecret,
    disableTokenCache: true,
  });

  return await client.bitable.v1.appTableRecord.delete(
    {
      path: {
        app_token: "Gku8bF1Z7aLYmgsCkXsccRb3nyd",
        table_id: "tblPT6wWAjPf8vY5",
        record_id,
      }
    },
    lark.withTenantToken(tenant_access_token)
  );
}

async function delTRecord(ctx) {
  const internalRes = await axios.post(
    "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal",
    {
      app_id: serverConfig.config.appId,
      app_secret: serverConfig.config.appSecret,
    },
    { headers: { "Content-Type": "application/json" } }
  );

  if (!internalRes.data) {
    ctx.body = serverUtil.failResponse("tenant_access_token request error");
    return;
  }
  if (internalRes.data.code != 0) {
    ctx.body = serverUtil.failResponse(
      `tenant_access_token request error: ${internalRes.data.msg}`
    );
    return;
  }

  // console.log(`internalRes`, internalRes);

  console.log(
    `接入服务方第③ 步: 获得颁发的自建应用授权凭证tenant_access_token`,
    internalRes.data.tenant_access_token
  );
  const tenant_access_token = internalRes.data.tenant_access_token || "";
  //获取自建应用授权凭证tenant_access_token结束

  // serverUtil.configAccessControl(ctx);
  const res = await reqDelTRecord(tenant_access_token, ctx.query.record_id);
  console.log("删除记录的响应结果：", res);
  ctx.body = res;
}

//在多维表格中新增一条记录
async function reqAddTRecord(tenant_access_token, record) {
  console.log("添加的新纪录：", record);
  // 开发者复制该Demo后，需要修改Demo里面的"app id", "app secret"为自己应用的appId, appSecret
  const client = new lark.Client({
    appId: serverConfig.config.appId,
    appSecret: serverConfig.config.appSecret,
    disableTokenCache: true,
  });

  return await client.bitable.v1.appTableRecord.create(
    {
      path: {
        app_token: "Gku8bF1Z7aLYmgsCkXsccRb3nyd",
        table_id: "tblwXtPtoHjPVuPP",
      },
      params: {
        user_id_type: 'open_id',
        ignore_consistency_check: true,
      },
      data: {
        fields: { "客户名称": record.companyName, "处理人": record.handler, "产品评价": record.productEvaluation, "使用评价": record.productEvaluation, "交期评价": record.productEvaluation, "培训评价": record.productEvaluation, "服务态度": record.serviceAttitude, "整体评价": record.overallEvaluation, "技能水平": record.skillLevels, "响应速度": record.responseSpeed, "建议与反馈": record.suggestion }
        // fields: { "客户名称": record.companyName, "产品满意度": record.productEvaluationValue, "使用满意度": record.productEvaluationValue, "交期满意度": record.productEvaluationValue, "培训满意度": record.productEvaluationValue, "服务满意度": record.serviceAttitudeValue, }
        // fields:new Map([['客户名称',record.companyName],['处理人',[record.handler]],['产品满意度',record.productEvaluationValue],['使用满意度',record.usageEvaluationValue],['交期满意度',record.deliveryDateEvaluationValue],['培训满意度',record.trainEvaluationValue],['服务满意度',record.serviceAttitudeValue],['附件',[]],['是否有意愿再次合作','是']]),
      }
    },
    lark.withTenantToken(tenant_access_token)
  );
}

async function addTRecord(ctx) {
  const internalRes = await axios.post(
    "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal",
    {
      app_id: serverConfig.config.appId,
      app_secret: serverConfig.config.appSecret,
    },
    { headers: { "Content-Type": "application/json" } }
  );

  if (!internalRes.data) {
    ctx.body = serverUtil.failResponse("tenant_access_token request error");
    return;
  }
  if (internalRes.data.code != 0) {
    ctx.body = serverUtil.failResponse(
      `tenant_access_token request error: ${internalRes.data.msg}`
    );
    return;
  }

  // console.log(`internalRes`, internalRes);

  console.log(
    `接入服务方第③ 步: 获得颁发的自建应用授权凭证tenant_access_token`,
    internalRes.data.tenant_access_token
  );
  const tenant_access_token = internalRes.data.tenant_access_token || "";
  //获取自建应用授权凭证tenant_access_token结束
  // serverUtil.configAccessControl(ctx);
  const data = ctx.request.body;
  console.log('收到的数据:', data);
  // 假设返回给客户端相同的数据作为响应
  const res = await reqAddTRecord(tenant_access_token, ctx.request.body);
  console.log("添加记录的响应结果：", res);
  ctx.body = res;
  // ctx.body = { message: 'POST 成功', success: true };
}

//列出自定义角色(控制台上的报错就是因为这个请求)
async function getRoleList(ctx) {
  const lark = require('@larksuiteoapi/node-sdk');
  const client = new lark.Client({
    appId: serverConfig.config.appId,
    appSecret: serverConfig.config.appSecret,
    disableTokenCache: true
  });
  // 还可以使用迭代器的方式便捷的获取数据，无需手动维护page_token
  (async () => {
    for await (const item of await client.base.v2.appRole.listWithIterator({
      path: {
        app_token: 'Gku8bF1Z7aLYmgsCkXsccRb3nyd',
      },
      params: {
        page_size: 10,
      },
    },
      lark.withTenantToken(ctx.query.user_access_token)
    )) {
      console.log("自定义角色", item);
    }
  })();
}

//更新自定义角色
function reqUpdatePermission() {


  // const lark = require('@larksuiteoapi/node-sdk');
  // const client = new lark.Client({
  //   appId: serverConfig.config.appId,
  //   appSecret: serverConfig.config.appSecret,
  //   disableTokenCache: true
  // });

  // console.log("tableData：",tableData,"tableData.length：",tableData.length);

  // tableData.forEach(async record => {
  //   if (record.fields.发起人[0].name == record.fields.处理人[0].name) {
  //     const res1 = await client.base.v2.appRole.update({
  //       path: {
  //         app_token: 'Gku8bF1Z7aLYmgsCkXsccRb3nyd',
  //         role_id: 'rolHMAS6Gp', //区域负责人角色id
  //       },
  //       data: {
  //         "role_name": "区域负责人",
  //         "table_roles": [
  //           {
  //             "table_perm": 2,
  //             "table_name": "工单管理总表",
  //             "table_id": "tblPT6wWAjPf8vY5",
  //             "field_perm": {
  //               "客户名称": 1,
  //               "客户联系人": 1,
  //               "客户电话": 1,
  //               "客户地址": 1,
  //               "服务方式": 1,
  //               "指派工作内容": 1,
  //               "处理人": 1,
  //               "我的工作内容": 3,
  //               "工作结果": 3,
  //               "设备型号": 3,
  //               "机身编号": 3,
  //               "软件未解决": 3,
  //               "软件已解决": 3,
  //               "硬件已解决": 3,
  //               "硬件未解决": 3
  //             }
  //           }
  //         ]
  //       }
  //     },
  //       lark.withTenantToken("t-g1046palOZ4VRRXCS3REJKZP3PCS3BJI6RJGSMZS")
  //     )
  //     console.log("res1", res1);
  //   } else {
  //     const res2 = await client.base.v2.appRole.update({
  //       path: {
  //         app_token: 'Gku8bF1Z7aLYmgsCkXsccRb3nyd',
  //         role_id: 'rolHMAS6Gp', //区域负责人角色id
  //       },
  //       data: {
  //         role_name: '区域负责人',
  //         table_roles: [
  //           {
  //             "table_perm": 2, //可编辑
  //             "table_name": "工单管理总表",
  //             "table_id": "tblPT6wWAjPf8vY5",
  //             "field_perm": {
  //               "客户名称": 1,
  //               "客户联系人": 1,
  //               "客户电话": 1,
  //               "客户地址": 1,
  //               "服务方式": 1,
  //               "指派工作内容": 1,
  //               "处理人": 1,
  //               "我的工作内容": 1,
  //               "工作结果": 1,
  //               "设备型号": 1,
  //               "机身编号": 1,
  //               "软件未解决": 1,
  //               "软件已解决": 1,
  //               "硬件已解决": 1,
  //               "硬件未解决": 1
  //             },
  //           }
  //         ]
  //       },
  //     },
  //       lark.withTenantToken("t-g1046palOZ4VRRXCS3REJKZP3PCS3BJI6RJGSMZS")
  //     )
  //     console.log("res2", res2);
  //   }
  // })
}

async function updatePermission() {
  const internalRes = await axios.post(
    "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal",
    {
      app_id: serverConfig.config.appId,
      app_secret: serverConfig.config.appSecret,
    },
    { headers: { "Content-Type": "application/json" } }
  );

  if (!internalRes.data) {
    ctx.body = serverUtil.failResponse("tenant_access_token request error");
    return;
  }
  if (internalRes.data.code != 0) {
    ctx.body = serverUtil.failResponse(
      `tenant_access_token request error: ${internalRes.data.msg}`
    );
    return;
  }

  // console.log(`internalRes`, internalRes);

  console.log(
    `接入服务方第③ 步: 获得颁发的自建应用授权凭证tenant_access_token`,
    internalRes.data.tenant_access_token
  );
  const tenant_access_token = internalRes.data.tenant_access_token || "";
  //获取自建应用授权凭证tenant_access_token结束
  // serverUtil.configAccessControl(ctx);
  await reqUpdatePermission();
  // ctx.body = res;
}

//发送短信
async function sendMessage(ctx) {

  // 发送短信
  const { phone, recordId, record_id } = ctx.request.body;
  console.log("飞书传递的record_id", typeof record_id, record_id);
  if (!phone || !recordId) {
    ctx.status = 400;
    ctx.body = { error: '缺少手机号或记录id' };
    return;
  }

  try {
    console.log("飞书传递的record_id", record_id);
    console.log("飞书传递的phone", phone);
    //把record_id存储到session中
    // ctx.session.tempId = record_id;
    // 把记录id存入Redis，有效期 5 分钟
    // await redis.setex('flybook_temp_id', 300, record_id);
    //把记录id存到多维表格中
    await updateMappingRecordId(record_id);

    const params = {
      // 需要替换成为您接收短信的手机号码 
      phoneNumbers: phone,
      // 需要替换成为您的短信签名
      signName: "深圳市劲拓自动化设备股份",
      // 需要替换成为您的短信模板code
      templateCode: "SMS_489715066",
      templateParam: JSON.stringify({ recordId })  // 动态参数
    };

    console.log("params", params);

    // 创建请求对象并设置入参
    let sendSmsRequest = new Dysmsapi20170525.SendSmsRequest(params);

    // 创建运行时参数
    let runtime = new Util.RuntimeOptions({});
    let client = Client.createClient();
    // 发起请求   
    const response = await client.sendSmsWithOptions(sendSmsRequest, runtime);
    console.log('短信发送响应:', response);
    if (response.body.code === 'OK') {
      ctx.body = { success: true, message: '短信发送成功' };
    } else {
      ctx.body = { success: false, message: response.body.message };
    }
  } catch (error) {
    console.error('发送短信失败:', error);
    ctx.status = 500;
    ctx.body = { error: '发送短信失败' };
  }
}

//获取多维表格指定数据表的数据
async function reqGetMappingRecordId(tenant_access_token) {
  const client = new lark.Client({
    appId: serverConfig.config.appId,
    appSecret: serverConfig.config.appSecret,
    disableTokenCache: true,
  });

  return await client.bitable.v1.appTableRecord.search(
    {
      path: {
        app_token: "EKlUbyMitac2R6s99ebcZ1qOnve",
        table_id: "tblksFYkk1kvIxXP",
      },
      params: {
        user_id_type: "open_id",
      },
      data: {
        field_names: ['记录id'],
      },
    },
    lark.withTenantToken(tenant_access_token)
  );
}

//从记录id映射表中获取记录id返回给前端
async function getMappingRecordId(ctx) {
  console.log(
    "\n-------------------[return record_id]-----------------------------"
  );
  // serverUtil.configAccessControl(ctx);
  //从session中读取记录id
  // const id = ctx.session.tempId;
  // const id = await redis.get('flybook_temp_id');
  // if (!id) {
  //   ctx.status = 404;
  //   ctx.body = { error: '记录ID不存在，请先发送短信' };
  //   return;
  // }
  // ctx.body = { id };

  //【请求】tenant_access_token：https://open.feishu.cn/document/ukTMukTMukTM/ukDNz4SO0MjL5QzM/auth-v3/auth/tenant_access_token_internal
  const internalRes = await axios.post(
    "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal",
    {
      app_id: serverConfig.config.appId,
      app_secret: serverConfig.config.appSecret,
    },
    { headers: { "Content-Type": "application/json" } }
  );

  if (!internalRes.data) {
    ctx.body = serverUtil.failResponse("tenant_access_token request error");
    return;
  }
  if (internalRes.data.code != 0) {
    ctx.body = serverUtil.failResponse(
      `tenant_access_token request error: ${internalRes.data.msg}`
    );
    return;
  }

  // console.log(`internalRes`, internalRes);

  console.log(
    `接入服务方第③ 步: 获得颁发的自建应用授权凭证tenant_access_token`,
    internalRes.data.tenant_access_token
  );
  const tenant_access_token = internalRes.data.tenant_access_token || "";
  //获取自建应用授权凭证tenant_access_token结束
  // serverUtil.configAccessControl(ctx);
  const duoweitable = await reqGetMappingRecordId(tenant_access_token);
  if (duoweitable && duoweitable.data.items.length > 0) {
    console.log("多维表格数据:", duoweitable.data.items);
    ctx.body = duoweitable.data.items;
  } else {
    ctx.body = "多维表格数据为空!";
  }


}

//更改多维表格记录id映射表
async function reqUpdateMappingRecordId(tenant_access_token, record_id) {
  console.log("timestamp", typeof timestamp);
  // 开发者复制该Demo后，需要修改Demo里面的"app id", "app secret"为自己应用的appId, appSecret
  const client = new lark.Client({
    appId: serverConfig.config.appId,
    appSecret: serverConfig.config.appSecret,
    disableTokenCache: true,
  });

  return await client.bitable.v1.appTableRecord.update(
    {
      path: {
        app_token: "EKlUbyMitac2R6s99ebcZ1qOnve",
        table_id: "tblksFYkk1kvIxXP",
        record_id: "recZnHxv8E",
      },
      params: {
        user_id_type: "open_id",
        ignore_consistency_check: false,
      },
      data: {
        fields: { "记录id": `${record_id}` }
      },
    },
    lark.withTenantToken(tenant_access_token)
  );
}

async function updateMappingRecordId(record_id) {
  const internalRes = await axios.post(
    "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal",
    {
      app_id: serverConfig.config.appId,
      app_secret: serverConfig.config.appSecret,
    },
    { headers: { "Content-Type": "application/json" } }
  );

  if (!internalRes.data) {
    ctx.body = serverUtil.failResponse("tenant_access_token request error");
    return;
  }
  if (internalRes.data.code != 0) {
    ctx.body = serverUtil.failResponse(
      `tenant_access_token request error: ${internalRes.data.msg}`
    );
    return;
  }

  // console.log(`internalRes`, internalRes);

  console.log(
    `接入服务方第③ 步: 获得颁发的自建应用授权凭证tenant_access_token`,
    internalRes.data.tenant_access_token
  );
  const tenant_access_token = internalRes.data.tenant_access_token || "";

  //获取自建应用授权凭证tenant_access_token结束
  // serverUtil.configAccessControl(ctx);
  const res = await reqUpdateMappingRecordId(tenant_access_token, record_id);
  console.log("修订记录id映射表：", res);
}


//测试接口
async function getHello(ctx) {
  console.log(
    "\n-------------------[hello world BEGIN]-----------------------------", ctx.query
  );
  // serverUtil.configAccessControl(ctx);
  if (ctx.query.handler !== ctx.query.trigger) {
    ctx.body = { status: "500", message: "ok" };
  } else {
    ctx.body = { status: "200", message: "ok" };
  }
}

//发送飞书消息
async function reqSendFeiShuMsg(tenant_access_token, user_id, order_id, record_url, final_order_status, refuse_reason, no_approved_reason) {

  const lark = require('@larksuiteoapi/node-sdk');
  const client = new lark.Client({
    appId: serverConfig.config.appId,
    appSecret: serverConfig.config.appSecret,
    disableTokenCache: true
  });

  //发送文本消息
  // const content = JSON.stringify({
  //   text: `${order_id}长时间没有处理，请抓紧处理`,
  //   url: record_url
  // });

  //发送卡片内容
  // const content = JSON.stringify({
  //   type: `template`,
  //   data: {
  //     template_id: "AAqIkBz3xDdhL", //卡片模板id
  //     template_version_name: "1.0.2", //版本号
  //     template_variable: {//卡片绑定的变量
  //       "title": "工单催办",
  //       order_id,
  //       "record_url": {
  //         "url": `${record_url}`,
  //       }
  //     },
  //   },
  // });

  let content = "";
  //根据不同的工单状态，装配不同的卡片内容
  if (final_order_status == "待接单") {
    content = JSON.stringify({
      type: `template`,
      data: {
        template_id: "AAqIkBz3xDdhL", //卡片模板id
        template_version_name: "1.0.2", //版本号
        template_variable: {//卡片绑定的变量
          "title": "工单待接受",
          "order_id": `你有一条工单待接受，请及时处理`,
          "record_url": {
            "url": `${record_url}`,
          }
        },
      },
    });
    return client.im.v1.message.create({
      params: {
        receive_id_type: 'open_id',
      },
      data: {
        receive_id: user_id,
        msg_type: 'interactive',
        // content: `{"text":"${order_id}长时间没有处理，请抓紧处理,可点击${record_url}查看"}`,
        content,
        // uuid: '选填，每次调用前请更换，如a0d69e20-1dd1-458b-k525-dfeca4015204',
      },
    },
      lark.withTenantToken(tenant_access_token)
    )
  } else if (final_order_status == "待审核") {
    content = JSON.stringify({
      type: `template`,
      data: {
        template_id: "AAqIkBz3xDdhL", //卡片模板id
        template_version_name: "1.0.2", //版本号
        template_variable: {//卡片绑定的变量
          "title": "工单审核",
          "order_id": `${order_id}待审核,请及时审核`,
          "record_url": {
            "url": `${record_url}`,
          }
        },
      },
    });
    return client.im.v1.message.create({
      params: {
        receive_id_type: 'open_id',
      },
      data: {
        receive_id: user_id,
        msg_type: 'interactive',
        // content: `{"text":"${order_id}长时间没有处理，请抓紧处理,可点击${record_url}查看"}`,
        content,
        // uuid: '选填，每次调用前请更换，如a0d69e20-1dd1-458b-k525-dfeca4015204',
      },
    },
      lark.withTenantToken(tenant_access_token)
    )
  } else if (final_order_status == "已拒绝") {
    content = JSON.stringify({
      type: `template`,
      data: {
        template_id: "AAqIkBz3xDdhL", //卡片模板id
        template_version_name: "1.0.2", //版本号
        template_variable: {//卡片绑定的变量
          "title": "工单拒绝",
          "order_id": `你派遣的${order_id}被拒绝,拒绝原因：${refuse_reason}`,
          "record_url": {
            "url": `${record_url}`,
          }
        },
      },
    });
    return client.im.v1.message.create({
      params: {
        receive_id_type: 'open_id',
      },
      data: {
        receive_id: user_id,
        msg_type: 'interactive',
        // content: `{"text":"${order_id}长时间没有处理，请抓紧处理,可点击${record_url}查看"}`,
        content,
        // uuid: '选填，每次调用前请更换，如a0d69e20-1dd1-458b-k525-dfeca4015204',
      },
    },
      lark.withTenantToken(tenant_access_token)
    )
  } else if (final_order_status == "已完结") {
    content = JSON.stringify({
      type: `template`,
      data: {
        template_id: "AAqIkBz3xDdhL", //卡片模板id
        template_version_name: "1.0.2", //版本号
        template_variable: {//卡片绑定的变量
          "title": "工单完结",
          "order_id": `${order_id}已完结,请知悉`,
          "record_url": {
            "url": `${record_url}`,
          }
        },
      },
    });
    return client.im.v1.message.create({
      params: {
        receive_id_type: 'open_id',
      },
      data: {
        receive_id: user_id,
        msg_type: 'interactive',
        // content: `{"text":"${order_id}长时间没有处理，请抓紧处理,可点击${record_url}查看"}`,
        content,
        // uuid: '选填，每次调用前请更换，如a0d69e20-1dd1-458b-k525-dfeca4015204',
      },
    },
      lark.withTenantToken(tenant_access_token)
    )
  } else if (final_order_status == "审核不通过") {
    content = JSON.stringify({
      type: `template`,
      data: {
        template_id: "AAqIkBz3xDdhL", //卡片模板id
        template_version_name: "1.0.2", //版本号
        template_variable: {//卡片绑定的变量
          "title": "审核不通过",
          "order_id": `${order_id}审核不通过,请及时查看,驳回原因为：${no_approved_reason}`,
          "record_url": {
            "url": `${record_url}`,
          }
        },
      },
    });
    return client.im.v1.message.create({
      params: {
        receive_id_type: 'open_id',
      },
      data: {
        receive_id: user_id,
        msg_type: 'interactive',
        // content: `{"text":"${order_id}长时间没有处理，请抓紧处理,可点击${record_url}查看"}`,
        content,
        // uuid: '选填，每次调用前请更换，如a0d69e20-1dd1-458b-k525-dfeca4015204',
      },
    },
      lark.withTenantToken(tenant_access_token)
    )
  }

}

async function sendFeiShuMsg(tenant_access_token, flag, record_id, record_url, order_id, final_order_status, refuse_reason, no_approved_reason) {
  const person = await reqGetTRecords(tenant_access_token, [record_id]);
  // console.log("person", person.data.records);
  const handler_user_id = person.data.records[0].fields.处理人[0].id;
  const creater_user_id = person.data.records[0].fields.发起人[0].id;
  if (flag == 1) {//给发起人发消息
    await reqSendFeiShuMsg(tenant_access_token, creater_user_id, order_id, record_url, final_order_status, refuse_reason, no_approved_reason);
  } else {//给处理人发消息
    await reqSendFeiShuMsg(tenant_access_token, handler_user_id, order_id, record_url, final_order_status, refuse_reason, no_approved_reason);
  }
  // ctx.body = { status: "200", message: "ok" };
}

// -------------------------------------------记录状态变更------------------------------------------------------------------------
async function reqUpdateOrderStatus(tenant_access_token, record_id, order_status) {
  // 开发者复制该Demo后，需要修改Demo里面的"app id", "app secret"为自己应用的appId, appSecret
  const client = new lark.Client({
    appId: serverConfig.config.appId,
    appSecret: serverConfig.config.appSecret,
    disableTokenCache: true,
  });

  return await client.bitable.v1.appTableRecord.update(
    {
      path: {
        app_token: "Gku8bF1Z7aLYmgsCkXsccRb3nyd",
        table_id: "tblPT6wWAjPf8vY5",
        record_id,
      },
      params: {
        user_id_type: "open_id",
        ignore_consistency_check: false,
      },
      data: {
        fields: { "工单状态": order_status }
      },
    },
    lark.withTenantToken(tenant_access_token)
  );
}

async function updateOrderStatus(ctx) {

  console.log("ctx", ctx.query);

  switch (ctx.query.final_order_status) {
    case '待接单':
      const internalRes = await axios.post(
        "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal",
        {
          app_id: serverConfig.config.appId,
          app_secret: serverConfig.config.appSecret,
        },
        { headers: { "Content-Type": "application/json" } }
      );

      if (!internalRes.data) {
        ctx.body = serverUtil.failResponse("tenant_access_token request error");
        return;
      }
      if (internalRes.data.code != 0) {
        ctx.body = serverUtil.failResponse(
          `tenant_access_token request error: ${internalRes.data.msg}`
        );
        return;
      }
      console.log(
        `接入服务方第③ 步: 获得颁发的自建应用授权凭证tenant_access_token`,
        internalRes.data.tenant_access_token
      );
      const tenant_access_token = internalRes.data.tenant_access_token || "";
      await reqUpdateOrderStatus(tenant_access_token, ctx.query.record_id, ctx.query.final_order_status);
      // await sendFeiShuMsg(tenant_access_token, 0, ctx.query.record_id, ctx.query.record_url, ctx.query.order_id, ctx.query.final_order_status);
      ctx.body = { status: "200", message: "ok" };
      break;

    case '待处理':
      if (ctx.query.handler !== ctx.query.trigger) {
        ctx.body = { status: "500", message: "你没有权限操作此记录" };
        return;
      } else {
        const internalRes = await axios.post(
          "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal",
          {
            app_id: serverConfig.config.appId,
            app_secret: serverConfig.config.appSecret,
          },
          { headers: { "Content-Type": "application/json" } }
        );
        if (!internalRes.data) {
          ctx.body = serverUtil.failResponse("tenant_access_token request error");
          return;
        }
        if (internalRes.data.code != 0) {
          ctx.body = serverUtil.failResponse(
            `tenant_access_token request error: ${internalRes.data.msg}`
          );
          return;
        }
        console.log(
          `接入服务方第③ 步: 获得颁发的自建应用授权凭证tenant_access_token`,
          internalRes.data.tenant_access_token
        );
        const tenant_access_token = internalRes.data.tenant_access_token || "";
        const res = await reqUpdateOrderStatus(tenant_access_token, ctx.query.record_id, ctx.query.final_order_status);
        console.log("响应", res);
        // await sendFeiShuMsg(tenant_access_token, ctx.query.record_id, ctx.query.record_url, ctx.query.order_id, ctx.query.final_order_status);
        // ctx.body = { status: "200", message: "ok" };
      }
      break;

    case '待审核':
      if (ctx.query.trigger !== ctx.query.creater) {// 操作按钮者不是工单的发起人
        ctx.body = { "status": "500", "title": "操作失败", "message": "你没有权限操作此记录" };
        return;
      } else {// 操作按钮者是工单的发起人
        const internalRes = await axios.post(
          "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal",
          {
            app_id: serverConfig.config.appId,
            app_secret: serverConfig.config.appSecret,
          },
          { headers: { "Content-Type": "application/json" } }
        );
        if (!internalRes.data) {
          ctx.body = serverUtil.failResponse("tenant_access_token request error");
          return;
        }
        if (internalRes.data.code != 0) {
          ctx.body = serverUtil.failResponse(
            `tenant_access_token request error: ${internalRes.data.msg}`
          );
          return;
        }
        console.log(
          `接入服务方第③ 步: 获得颁发的自建应用授权凭证tenant_access_token`,
          internalRes.data.tenant_access_token
        );
        const tenant_access_token = internalRes.data.tenant_access_token || "";
        const res = await reqUpdateOrderStatus(tenant_access_token, ctx.query.record_id, ctx.query.final_order_status);
        console.log("响应", res);
        // await sendFeiShuMsg(tenant_access_token, 1, ctx.query.record_id, ctx.query.record_url, ctx.query.order_id, ctx.query.final_order_status);
        // ctx.body = { "status": "200", "title": "工单完结", "message": `${ctx.query.order_id}已审核通过`, "url": ctx.query.record_url };
      }
      break;

    case '已完结':
      if (ctx.query.trigger !== ctx.query.creater) {// 操作按钮者不是工单的发起人
        ctx.body = { "status": "500", "title": "操作失败", "message": "你没有权限操作此记录" };
        return;
      } else {// 操作按钮者是工单的发起人
        const internalRes = await axios.post(
          "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal",
          {
            app_id: serverConfig.config.appId,
            app_secret: serverConfig.config.appSecret,
          },
          { headers: { "Content-Type": "application/json" } }
        );
        if (!internalRes.data) {
          ctx.body = serverUtil.failResponse("tenant_access_token request error");
          return;
        }
        if (internalRes.data.code != 0) {
          ctx.body = serverUtil.failResponse(
            `tenant_access_token request error: ${internalRes.data.msg}`
          );
          return;
        }
        console.log(
          `接入服务方第③ 步: 获得颁发的自建应用授权凭证tenant_access_token`,
          internalRes.data.tenant_access_token
        );
        const tenant_access_token = internalRes.data.tenant_access_token || "";
        const res = await reqUpdateOrderStatus(tenant_access_token, ctx.query.record_id, ctx.query.final_order_status);
        console.log("响应", res);
        // await sendFeiShuMsg(tenant_access_token, 0, ctx.query.record_id, ctx.query.record_url, ctx.query.order_id, ctx.query.final_order_status);
        // ctx.body = { "status": "200", "title": "工单完结", "message": `${ctx.query.order_id}已审核通过`, "url": ctx.query.record_url };
      }
      break;

    case '审核不通过':
      if (ctx.query.trigger !== ctx.query.creater) {// 操作按钮者不是工单的发起人
        ctx.body = { "status": "500", "title": "操作失败", "message": "你没有权限操作此记录" };
        return;
      } else {// 操作按钮者是工单的发起人
        const internalRes = await axios.post(
          "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal",
          {
            app_id: serverConfig.config.appId,
            app_secret: serverConfig.config.appSecret,
          },
          { headers: { "Content-Type": "application/json" } }
        );
        if (!internalRes.data) {
          ctx.body = serverUtil.failResponse("tenant_access_token request error");
          return;
        }
        if (internalRes.data.code != 0) {
          ctx.body = serverUtil.failResponse(
            `tenant_access_token request error: ${internalRes.data.msg}`
          );
          return;
        }
        console.log(
          `接入服务方第③ 步: 获得颁发的自建应用授权凭证tenant_access_token`,
          internalRes.data.tenant_access_token
        );
        const tenant_access_token = internalRes.data.tenant_access_token || "";
        const res = await reqUpdateOrderStatus(tenant_access_token, ctx.query.record_id, "待处理");
        console.log("响应", res);
        // await sendFeiShuMsg(tenant_access_token, 0, ctx.query.record_id, ctx.query.record_url, ctx.query.order_id, ctx.query.final_order_status, ctx.query.refuse_reason, ctx.query.no_approved_reason);
        // ctx.body = { "status": "200", "title": "工单完结", "message": `${ctx.query.order_id}已审核通过`, "url": ctx.query.record_url };
      }
      break;

    case '已拒绝':
      if (ctx.query.handler !== ctx.query.trigger) {
        ctx.body = {
          accepter: ctx.query.trigger, status: "500", title: "操作失败", message: "你没有权限操作此记录"
        };
        return;
      } else {
        const internalRes = await axios.post(
          "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal",
          {
            app_id: serverConfig.config.appId,
            app_secret: serverConfig.config.appSecret,
          },
          { headers: { "Content-Type": "application/json" } }
        );
        if (!internalRes.data) {
          ctx.body = serverUtil.failResponse("tenant_access_token request error");
          return;
        }
        if (internalRes.data.code != 0) {
          ctx.body = serverUtil.failResponse(
            `tenant_access_token request error: ${internalRes.data.msg}`
          );
          return;
        }
        console.log(
          `接入服务方第③ 步: 获得颁发的自建应用授权凭证tenant_access_token`,
          internalRes.data.tenant_access_token
        );
        const tenant_access_token = internalRes.data.tenant_access_token || "";
        const res = await reqUpdateOrderStatus(tenant_access_token, ctx.query.record_id, ctx.query.final_order_status);
        console.log("拒绝的响应：", res);
        // await sendFeiShuMsg(tenant_access_token, 1, ctx.query.record_id, ctx.query.record_url, ctx.query.order_id, ctx.query.final_order_status, ctx.query.refuse_reason);
        // ctx.body = { accepter: ctx.query.creater, status: "200", title: `工单被拒绝`, message: `你派遣的${ctx.query.order_id}被拒绝,拒绝原因：${ctx.query.refuse_reason}` };
      }
      break;

    default:
      break;
  }

}

///Start Sever
const app = new Koa();
const router = new Router();

// 使用 bodyparser 中间件
app.use(bodyParser());

//配置Session的中间件
app.keys = ["some secret hurr"]; /*cookie的签名*/
const koaSessionConfig = {
  key: "lk_koa:session" /** 默认 */,
  maxAge: 2 * 3600 * 1000 /*  cookie的过期时间，单位 ms  */,
  overwrite: true /** (boolean) can overwrite or not (default true)  默认 */,
  httpOnly: true /**  true表示只有服务器端可以获取cookie */,
  signed: true /** 默认 签名 */,
  rolling: true /** 在每次请求时强行设置 cookie，这将重置 cookie 过期时间（默认：false） 【需要修改】 */,
  renew: false /** (boolean) renew session when session is nearly expired      【需要修改】*/,
};
app.use(session(koaSessionConfig, app));

// app.use(cors({
//   origin: 'http://192.168.150.229:3000', // 替换为飞书应用配置的域名
// }));

// 启用CORS（允许所有来源）
// app.use(cors());

//注册服务端路由和处理
// router.get("/duowei", getDuoWei);

router.get(serverConfig.config.getUserAccessTokenPath, getUserAccessToken);
router.get(serverConfig.config.getSignParametersPath, getSignParameters);

// 定义路由
router.get("/api/get_role_list", getRoleList);
router.get("/api/duoweiList", getDuoWeiList);
router.get("/api/updateTRecord", updateTRecord);
router.get("/api/delTRecord", delTRecord);
router.post("/api/addTRecord", addTRecord);
router.post("/api/getTRecords", getTRecords);
//发送短信
router.post("/api/sendSms", sendMessage);
router.get("/api/updateOrderStatus", updateOrderStatus);
// router.get("/api/addTRecord", addTRecord);
router.get("/api/hello", getHello);
router.get("/api/sendFeiShuMsg", sendFeiShuMsg);
router.get("/api/getRecordId", getMappingRecordId);
var port = process.env.PORT || serverConfig.config.apiPort;


app.use(serverUtil.configAccessControl); // 必须放在路由之前

app.use(router.routes()).use(router.allowedMethods());
app.listen(port, () => {
  console.log(`server is start, listening on port ${port}`);
});
